package top.surgeqi.security.demo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import top.surgeqi.security.demo.bean.result.Result;
import top.surgeqi.security.demo.constants.SecurityError;
import top.surgeqi.security.jwt.contants.AuthConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p><em>Created by qipp on 2020/7/1 14:27</em></p>
 * 自定义权限不足处理器
 *
 * @author <a href="https://gitee.com/qipengpai">qipp</a>
 * @since 1.0.1
 */
@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * springmvc启动时自动装配json处理类
     */
    private final ObjectMapper objectMapper;

    public CustomAccessDeniedHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        // 无权限
        log.info("无权限 --->  CustomAccessDeniedHandler ");
        Result<Object> result = Result.failed(SecurityError.USER_PERMISSION_DENIED.getResCode(), SecurityError.USER_PERMISSION_DENIED.getResMsg());
        response.setContentType(AuthConstants.CONTENT_TYPE);
        response.getWriter().write(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
        response.getWriter().close();
    }
}